/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package wat.clientapp.remote;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.logging.Logger;
import wat.ziszcommon.remote.CryptoUtils;
import wat.ziszcommon.remote.JarProvider;
import wat.ziszcommon.remote.RemoteModuleFactory;

/**
 *
 * @author Marcin
 */
public class JarClassLoader extends ClassLoader {

    private JarProvider jarProvider;
    private String dirPath;

    public JarClassLoader() {
        super();
        Object proxy = RemoteModuleFactory.getInstance().createProxy(JarProvider.class);
        if (proxy instanceof JarProvider) {
            jarProvider = (JarProvider) proxy;
        }
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        URL url;
        try {
            url = new URL("");
            JarURLConnection connection = (JarURLConnection) url.openConnection();
            JarFile jarFile = connection.getJarFile();
            jarFile.getManifest();
            //JarResources jarResources = new JarResources (jarName);
        } catch (MalformedURLException ex) {
            Logger.getLogger(JarClassLoader.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(JarClassLoader.class.getName()).log(Level.SEVERE, null, ex);
        }


        try {
            Object[] objTab = jarProvider.getJar(name);
            if (objTab != null && objTab.length == 2) {
                byte[] data = (byte[]) objTab[0];
                String filename = (String) objTab[1];
                String md5 = (String) objTab[2];
                if (CryptoUtils.md5(data).equals(md5)) {
                    FileOutputStream fos = new FileOutputStream(dirPath + name + ".jar");
                    fos.write(data);
                    fos.close();
                }

            }
        } catch (Exception e) {
        }
        throw new ClassNotFoundException(name);
    }
}
